//
//  CYNewZFBVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/6/28.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYNewZFBVC.h"
#import "CYHttpTool.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "MBProgressHUD+LE.h"
#import "CXCarouselView.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "LEPhotoBrowserTool.h"
#import "CYImageShowView.h"
#import "MBProgressHUD+LE.h"
#import "UIImageView+WebCache.h"
#import "CYZFBFindVC.h"
#import "GCD.h"
#import "CXCarouselView.h"
#import "CustomIOSAlertView.h"

@interface CYNewZFBVC ()<UITextFieldDelegate>
@property (nonatomic, strong)CXCarouselView *cocxView;
@property (weak, nonatomic) IBOutlet UILabel *namelab;
@property (weak, nonatomic) IBOutlet UILabel *accountlab;
@property (weak, nonatomic) IBOutlet UITextField *numberTF;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UIButton *fuzhiBtn;

@property(nonatomic, strong) GCDTimer *GCDTimer;

@property (nonatomic, strong) NSString *zhibaobaoAccount;
@property (nonatomic, strong) NSString *zhifubaoName;
@property (nonatomic, strong) NSArray *picArr;
@property (weak, nonatomic) IBOutlet UIButton *czBtn;
@property (weak, nonatomic) IBOutlet UIView *imageView;
@property (nonatomic, assign) int timecount;
@property (nonatomic, assign) NSArray *detailArr;

@property (weak, nonatomic) IBOutlet UILabel *helplab;



@end

@implementation CYNewZFBVC

-(void)viewWillAppear:(BOOL)animated{

}

- (void)viewDidLoad {
     [super viewDidLoad];
     
     _fuzhiBtn.layer.cornerRadius = 5.0f;
     _numberTF.delegate = self;
     UIButton*rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,100,30)];
     rightButton.titleLabel.textColor = [UIColor blackColor];
     rightButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
     /**
     [rightButton addTarget:self action:@selector(ZFBclick) forControlEvents:UIControlEventTouchUpInside];
     [rightButton setTitle:@"联系我们" forState:UIControlStateNormal];
      **/
     UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.rightBarButtonItem= rightItem;
     _submitBtn.layer.cornerRadius = 5.0f;
     [self setupNavigationView];
     [self setupZFBStatues];

     //引导图 暂不做
//     [self showyindaotu];
     
     
    // Do any additional setup after loading the view from its nib.
}
-(void) showyindaotu{
     
     [CYHttpTool postWithURL:[CYURL shared].getZhifubao params:@{} success:^(id json) {
          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
          if (jsoninfo.isSuccess) {
               NSDictionary *dic = jsoninfo.data;
               _detailArr = [dic objectForKey:@"pics"];
               if (dic.count) {
                    [self loadshowview];
               }
          }
          
          
     } failure:^(NSError *error) {
          
     }];
}

-(void)loadshowview{
//     CGRectMake(0, 0,w, self.view.height-160)
//    CGFloat w = CYScreeSize.width - 32;
     _cocxView = [CXCarouselView initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-50) hasTimer:YES interval:5 placeHolder:[UIImage imageNamed:@"loading"]];
     [self.cocxView setupWithArray:_detailArr];
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     alertView.containerView = _cocxView;
     alertView.buttonTitles = @[@"跳过"];
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];

     
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
     //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
     [_numberTF resignFirstResponder];
     return YES;
     
}

- (IBAction)fuzhiBtnClick:(id)sender {
     UIPasteboard *pab = [UIPasteboard generalPasteboard];
     [pab setString:_zhibaobaoAccount];
     if (pab == nil) {
          [MBProgressHUD showError:@"复制失败"];
          
     }else
     {
          [MBProgressHUD showSuccess:@"已复制"];
          
     }
}



-(void)setupZFBStatues{
     
     [CYHttpTool postWithURL:[CYURL shared].getZhifubao params:@{} success:^(id json) {
          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
          NSDictionary *dic = jsoninfo.data;
          _zhifubaoName = [dic objectForKey:@"zhifubaoName"];
          _zhibaobaoAccount = [dic objectForKey:@"zhibaobaoAccount"];
          _helplab.text = [NSString stringWithFormat:@"2.在“对方账户”处填写“ %@”,再点击“下一步”",_zhibaobaoAccount];
          _namelab.text = [NSString stringWithFormat:@"姓名   %@", _zhifubaoName];
          _accountlab.text = [NSString stringWithFormat:@"账户   %@", _zhibaobaoAccount];
          
     } failure:^(NSError *error) {
          
     }];
}
/**
-(void)ZFBclick{
     if (_zhibaobaoAccount) {
//          NSString *str = [NSString stringWithFormat:@"如充值遇到问题，请在支付宝内添加:%@为好友,与我们联系",_zhibaobaoAccount];
//          CYAlertView(str);
          NSString *str = [NSString stringWithFormat:@"关注微信公众号“天下无赖诚信联盟”"];
          CYAlertView(str);
          
     }
     
}
 **/

- (void)setupNavigationView {
     
     UIView *naviView = [[UIView alloc] init];
     naviView.backgroundColor = CYNaviThemeColor;
     naviView.frame = CGRectMake(0, 0, self.view.width, 64);
     [self.view addSubview:naviView];
}
- (IBAction)findteachClick:(id)sender {
     CYZFBFindVC *findvc = [[CYZFBFindVC alloc]init];
     [self.navigationController pushViewController:findvc animated:YES];
     
}


- (IBAction)chongzhiteachClick:(id)sender {
     CYImageShowView *image = [[CYImageShowView alloc]init];
     [self.navigationController pushViewController:image animated:YES];
     
     
}
- (IBAction)submitClick:(id)sender {
     if (_numberTF.text.length == 0) {
          CYAlertView(@"请输入订单号");
          return;
     }
     //初始化
     NSDate *date = [NSDate date];
     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
     
     NSDictionary *lasttime = [[NSDictionary alloc] initWithContentsOfFile:@"timesp.plist"];
     NSString *lasttimeStr = [lasttime objectForKey:@"lasttime"];
     if (lasttime.count == 0) {
          //第一次进来，启动定时器
          [self countdown:sender];
          NSDictionary *timedic = @{@"lasttime":timeSp};
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString *plistPath1= [paths objectAtIndex:0];
          NSLog(@"%@",plistPath1);
          //得到完整的路径名
          NSString *fileName = [plistPath1 stringByAppendingPathComponent:@"timesp.plist"];
          //NSMutableDictionary *myDic = [[NSMutableDictionary alloc]init];
          //[myDic setValuesForKeysWithDictionary:cityDic];
          NSFileManager *fm = [NSFileManager defaultManager];
          
          if ([fm createFileAtPath:fileName contents:nil attributes:nil] ==YES) {
               [timedic writeToFile:fileName atomically:YES];
               NSLog(@"文件写入完成");
               
          }

          
     }
     if (lasttime.count > 0) {
          //开始做减法
          double aNumber = [timeSp doubleValue];
          double bNumber = [lasttimeStr doubleValue];
          _timecount = aNumber-bNumber;
          
          if (_timecount > 30) {
               //不需要
               NSDictionary *timedic = @{@"lasttime":timeSp};
               NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
               NSString *plistPath1= [paths objectAtIndex:0];
               NSLog(@"%@",plistPath1);
               //得到完整的路径名
               NSString *fileName = [plistPath1 stringByAppendingPathComponent:@"timesp.plist"];
               //NSMutableDictionary *myDic = [[NSMutableDictionary alloc]init];
               //[myDic setValuesForKeysWithDictionary:cityDic];
               NSFileManager *fm = [NSFileManager defaultManager];
               
               if ([fm createFileAtPath:fileName contents:nil attributes:nil] ==YES) {
                    [timedic writeToFile:fileName atomically:YES];
                    NSLog(@"文件写入完成");
                    
               }

          }else if(_timecount <30){
               //需要定时
               int cha = 30-_timecount;
               NSString *noticestr = [NSString stringWithFormat:@"请于%d秒后重新提交",cha];
               CYAlertView(noticestr);
               [self countdown1:sender];
               return;
               
          }
     }
          //可以提交
          CYUser *user = [CYLoginHttpTool userData].user;
          [CYHttpTool postWithURL:[CYURL shared].saveZhifubaoTradeRecharge params:@{@"userId":user.userId,@"token":user.token,@"tradeNo":_numberTF.text} success:^(id json) {
               CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
               if (jsoninfo.isSuccess) {
                    NSString *result = jsoninfo.message;
                    NSString *account = jsoninfo.data;
                    NSString *notice = [NSString stringWithFormat:@"%@ \n充值金额为:%@元",result,account];
                    NSFileManager* fileManager=[NSFileManager defaultManager];
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"timesp.plist"];
                    if (uniquePath) {
                         [fileManager removeItemAtPath:uniquePath error:nil];
                         
                    }
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"CYAssetAccountNotification" object:nil userInfo:nil];
                    CYAlertView(notice);
                    [self.navigationController popViewControllerAnimated:YES];
                    
               }else{
                    CYAlertView(jsoninfo.message);
                    [self countdown:sender];
               }
               
          } failure:^(NSError *error) {
               CYAlertView(@"网络错误");
               [self countdown:sender];

               
          }];
     
}

/**
 *  倒计时
 */
- (void)countdown:(UIButton *)btn {
     self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
     
     CYWeakObject(weakself, self);
     __block int time = 29;
     [self.GCDTimer event:^{
          if (time < 1) {
               //设置界面的按钮显示 根据自己需求设置
               [btn setTitle:@"完成充值" forState:UIControlStateNormal];
               btn.userInteractionEnabled = YES;
//               btn.backgroundColor = CYColor(79, 118, 245, 1);
               [weakself.GCDTimer destroy];
          } else {
               //        NSLog(@"time:%d", time);
               [btn setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
               btn.userInteractionEnabled = NO;
               //            btn.backgroundColor = CYColor(211, 211, 211, 1);
          }
          time--;
     } timeInterval:NSEC_PER_SEC * 1];
     [self.GCDTimer start];
}

/**
 *  倒计时
 */
- (void)countdown1:(UIButton *)btn1 {
     self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
     
     CYWeakObject(weakself, self);
     __block int time = 30-_timecount;
     [self.GCDTimer event:^{
          if (time < 1) {
               //设置界面的按钮显示 根据自己需求设置
               [btn1 setTitle:@"完成充值" forState:UIControlStateNormal];
               btn1.userInteractionEnabled = YES;
               //               btn.backgroundColor = CYColor(79, 118, 245, 1);
               [weakself.GCDTimer destroy];
          } else {
               //        NSLog(@"time:%d", time);
               [btn1 setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
               btn1.userInteractionEnabled = NO;
               //            btn.backgroundColor = CYColor(211, 211, 211, 1);
          }
          time--;
     } timeInterval:NSEC_PER_SEC * 1];
     [self.GCDTimer start];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
